const db = require('../mysql')

// 封装请求函数
function getData(name, sql, par = []) {
    return new Promise((resolve, reject) => {
        db.query(sql, par, (err, result) => {
            if (err) {
                reject(err.message)
            }
            if (result.length !== 0) {
                resolve({ name: name, data: result })
            }
        })
    })
}

// 获取首页所有数据
exports.getHomeData = (req, res) => {
    const getSwiperDataSql = 'SELECT * FROM swiper_data'
    const getNavListSql = 'SELECT * FROM class_category ORDER BY total_access DESC LIMIT 0,4'
    const getPopTeacherSql = 'SELECT * FROM teachers'
    const getRecentLearnSql = 'SELECT * FROM recent_learn'
    const SwiperData = getData('SwiperData', getSwiperDataSql)
    const NavListData = getData('NavListData', getNavListSql)
    const PopTeacherData = getData('PopTeacherData', getPopTeacherSql)
    const RecentLearnData = getData('RecentLearnData', getRecentLearnSql)

    Promise.all([SwiperData, NavListData, PopTeacherData, RecentLearnData]).then(value => {
        res.send({
            status: 200,
            data: value,
            message: 'Home页面数据获取成功'
        })
    }, reason => {
        res.cc(reason)
    })
}

// 加载更多最近学习
exports.getMoreRecentLearn = (req, res) => {
    res.send({
        message: '加载更多'
    })
    const getRecentLearnSql = 'SELECT * FROM recent_learn'
}

// 联想关键词功能
exports.search = (req, res) => {
    const keyword = req.query.keyword
    // console.log(keyword);
    if (!keyword) { res.cc('无相课程', 404) } else {
        const searchSql = `SELECT * FROM classes WHERE class_name LIKE "%${keyword}%"`
        db.query(searchSql, keyword, (err, result) => {
            if (err) res.cc(err)
            if (result.length !== 0) {
                res.send({
                    status: 200,
                    message: '搜索成功',
                    data: result
                })
            } else {
                res.cc('无相课程', 404)
            }

        })
    }
}
// 搜索课程
exports.searchClass = (req, res) => {
    const className = req.query.className
    console.log(className);
    if (!className) { res.cc('无相课程', 404) } else {
        const searchSql = `SELECT * FROM classes WHERE class_name LIKE "%${className}%"`
        db.query(searchSql, className, (err, result) => {
            if (err) res.cc(err)
            if (result.length !== 0) {
                res.send({
                    status: 200,
                    message: '搜索成功',
                    data: result
                })
            } else {
                res.cc('无相课程', 404)
            }

        })
    }
}